/*
 * All rights Reserved, Designed By HerDao
 * Copyright:    Copyright(C) 2020-2099
 * Company:      HerDao Ltd.
 */
package com.boots.redission.view;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.module.boots.api.message.ResponseMsg;
import com.module.boots.api.utils.MsgUtils;
import com.module.boots.exception.CommonRuntimeException;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * @author：OprCalf
 * @date：2021-1-9 15:29:02
 */
@Api(tags = { "web服务：分布式锁接口" })
@RestController
@RequestMapping("view/redission")
@Slf4j
public class RedissionView {

    @Autowired
    private RedissonClient redissonClient;

    /**
     *
     * @author OprCalf
     * @Date 2021-1-9 15:52:54
     * @param lockKey 锁密钥
     * @return ResponseMsg<String>
     */
    @ApiOperation(value = "获取加锁数据")
    @GetMapping(value = "/getLock", produces = MediaType.APPLICATION_JSON_VALUE)
    @SneakyThrows(CommonRuntimeException.class)
    public ResponseMsg<String> getLock(@RequestParam(value = "lockKey") String lockKey) {
        // 根据入参获取当前锁
        final RLock lock = redissonClient.getLock(lockKey);
        boolean getLock = false;
        try {
            // 开始加锁，最多等待2秒，上锁以后5秒自动解锁
            if (getLock = lock.tryLock(2, 5, TimeUnit.SECONDS)) {
                return MsgUtils.buildSuccessMsg("拿到锁成功");
            } else {
                return MsgUtils.buildFailureMsg("拿到锁失败");
            }
        }
        catch (final InterruptedException e) {
            return MsgUtils.buildFailureMsg("获取分布式锁发生异常");
        }
        finally {
            if (getLock) {
                lock.unlock();
                log.info("释放锁成功");
            }
        }
    }

}
